package com.cmcc.groupcontacts.database;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;

import com.cmcc.groupcontacts.util.AppManager;

/**
 * 数据库操作适配器
 * 
 * @author 
 * 
 */
public class DatabaseAdapter {
	// private static final String logTag = "DatabaseAdapter";
	public static final String DB_NAME = "database.db"; // 生成的数据库名称
	
	private Context context;
	private int dbVersion = 1; // 数据库版本号

	public DatabaseAdapter(Context context) throws SQLiteException {
		this.context = context;
		dbVersion = AppManager.getVerCode(context);
	}

	public DatabaseAdapter(Context context, int dbversion) throws SQLiteException {
		this.context = context;
		this.dbVersion = dbversion;
	}

	/**
	 * 获取可读写的数据库实例
	 * 
	 * @throws SQLiteException
	 */
	public SQLiteDatabase getWriteDbInstance() throws SQLiteException {
		DatabaseManager dbOpenHelper = new DatabaseManager(context, DB_NAME, null, dbVersion);
		SQLiteDatabase db = null;
		boolean isLock = true;
		int times = 0;
		while (isLock && times < 10) {
			try {
				db = dbOpenHelper.getWritableDatabase();
				if (db.isDbLockedByOtherThreads()) {// 如果库被其他线程锁住，等待并重新获取
					db.close();
					try {
						Thread.sleep(5);
					} catch (Exception e1) {
						e1.printStackTrace();
					}
				} else
					isLock = false;
			} catch (Exception e) {
				try {
					Thread.sleep(5);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
			}
			times++;
		}
		return db;
	}

	/**
	 * 获取只读数据库实例,用于查询数据使用
	 * 
	 * @return
	 * @throws SQLiteException
	 */
	public SQLiteDatabase getReadDbInstance() throws SQLiteException {
		DatabaseManager dbOpenHelper = new DatabaseManager(context, DB_NAME, null, dbVersion);
		SQLiteDatabase db = null;
		boolean isLock = true;
		int times = 0;
		while (isLock && times < 10) {
			try {
				db = dbOpenHelper.getReadableDatabase();
				if (db.isDbLockedByOtherThreads()) {// 如果库被其他线程锁住，等待并重新获取
					db.close();
					try {
						Thread.sleep(5);
					} catch (Exception e1) {
						e1.printStackTrace();
					}
				} else
					isLock = false;
			} catch (Exception e) {
				try {
					Thread.sleep(5);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
			}
			times++;
		}
		return db;
	}

	public void execSQL(String sql) {
		getWriteDbInstance().execSQL(sql);
	}

	public void close(SQLiteDatabase db) {
		if (db != null) {
			db.close();
			db = null;
		}
	}
}